package com.muatocroi.tornado;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class SendFileActivity extends ActivityMCAbstractClass implements OnClickListener, Runnable {
	
	private Handler uiHandler = new Handler();

	private static final int BUFFER_SIZE = 1024;
	private static final int PICKFILE_RESULT_CODE = 0x1;
	private static EditText txtFile;
	private static Button btnPickFile, btnSend;
	private static CheckBox chkOpen;
	private static ProgressBar progressBar;

	private static int maxProgress;
	private static int curProgress;

	private static String filePath = null;

	private static ServerSocket listener = null;
	private static FileInputStream fileStream;

	private static SignalSender sender = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_send_file);

		txtFile = (EditText) findViewById(R.id.txtFilePath);
		btnPickFile = (Button) findViewById(R.id.btnPickFile);
		btnSend = (Button) findViewById(R.id.btnSendFile);
		chkOpen = (CheckBox) findViewById(R.id.chkOpenFile);
		progressBar = (ProgressBar) findViewById(R.id.progressSending);

		btnPickFile.setOnClickListener(this);
		btnSend.setOnClickListener(this);
		txtFile.setEnabled(false);

		sender = SignalSender.getSender();
		if(!sender.isSending())
		{
			sender.BeginSend();
		}
	}
	@Override
	public void run() { // Thread Send File
		try {
			listener.setSoTimeout(3000);
			Socket skSend = listener.accept();
			listener.close();
			OutputStream ostream = skSend.getOutputStream();
			//Get file name from path
			String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
			byte[] bFileName = fileName.getBytes();

			byte[] bSize = intToByteArray(bFileName.length);
			//write how many size of file name
			ostream.write(bSize);
			//alway flush
			ostream.flush();
			//Write file name
			ostream.write(bFileName);

			int fileSize = (int) (new File(filePath).length());
			bSize = intToByteArray(fileSize);
			//File size
			ostream.write(bSize);
			ostream.flush();
			maxProgress = fileSize;
			curProgress = 0;
			uiHandler.post(new Runnable() {
				@Override
				public void run() {
					progressBar.setMax(maxProgress);
					progressBar.setProgress(curProgress);
				}
			});

			bSize = new byte[BUFFER_SIZE];

			int sentSize = 0;
			while (sentSize < fileSize) {
				int readed = fileStream.read(bSize);

				if (readed > 0)
					ostream.write(bSize, 0, readed);
				sentSize += readed;
				curProgress = sentSize;
				uiHandler.post(new Runnable() {
					@Override
					public void run() {
						progressBar.setProgress(curProgress);
					}
				});
			}

			fileStream.close();
			skSend.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		uiHandler.post(new Runnable() {
			@Override
			public void run() {
				btnPickFile.setEnabled(true);
				btnSend.setEnabled(true);
			}
		});
	}

	private static final byte[] intToByteArray(int value) {
		return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value };
	}

	private void sendFile() {

		if (filePath == null)
			return;

		try {
			fileStream = new FileInputStream(filePath);

			btnPickFile.setEnabled(false);
			btnSend.setEnabled(false);

			listener = new ServerSocket(0);

			Thread thrSendFile = new Thread(this);
			thrSendFile.start();

			InetAddress addr = AddressLocal.getLocals().get(0);
			int port = listener.getLocalPort();
			boolean open = chkOpen.isChecked();

			sender.Send(CommandSendFile.Address(addr));
			sender.Send(CommandSendFile.Port(port));
			sender.Send(CommandSendFile.Open(open));

		} catch (FileNotFoundException e) {
			Toast.makeText(
					this,
					"Can't open file, please choose other file or using other picker application!",
					Toast.LENGTH_SHORT).show();
			return;
		} catch (IOException e) {
			Toast.makeText( this, "Can't create socket, make sure you're having a network connection!",Toast.LENGTH_SHORT).show();
			return;
		}
	}

	private void pickFile() {
		try {
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("file/*");
			startActivityForResult(intent, PICKFILE_RESULT_CODE);
		} catch (Exception ex) {
			Toast.makeText(getBaseContext(), "No appropriate file browser!", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PICKFILE_RESULT_CODE:
				progressBar.setVisibility(View.VISIBLE);
				filePath = data.getData().getPath();
				txtFile.setText(filePath);
				curProgress = 0;
				progressBar.setProgress(curProgress);
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnPickFile:
			pickFile();
			break;

		case R.id.btnSendFile:
			sendFile();
			break;
		}
	}
}
